package com.kkb.cglibproxy;

import com.kkb.service.IService;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;


@Service("nbaService")
public class NBAService implements IService {

    public int add(String name,int id){
        System.out.println("NBAService----Add----");
        return id;
    }

    public static void main(String[] args) {
        NBAService service = new NBAService();
        NBAService proxyService = (NBAService) Enhancer.create(service.getClass(),
                new MethodInterceptor() {//回调函数编写代理规则
                    @Override
                    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                        try {
                            System.out.println("开始事务");
                            Object invoke = methodProxy.invokeSuper(o, objects);//核心业务
                            System.out.println("提交事务");
                            return invoke;
                        } catch (Throwable throwable) {
                            throwable.printStackTrace();
                            System.out.println("事务回滚");
                            throw throwable;
                        } finally {
                            System.out.println("finally---------");
                        }
                    }
                });
        int res = proxyService.add("湖人",1001);
        System.out.println(res);
    }

    @Override
    public void add() {

    }

    @Override
    public void add(int id, String name) {
        System.out.println("NBAService-----add----------");
    }

    @Override
    public boolean update(int num) {
        System.out.println("NBAService------update---------------");
        if (num>666){
            return true;
        }
        return false;
    }
}
